package com.weipai.demo.util;

import com.weipai.demo.model.DUser;
import com.weipai.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息sesion操作工具类
 * 为了适应spring-session 序列化，session中存储的除基本类型外的其他对象均采用Map对象
 *
 * @author gyt
 * @date 2017年8月26日 下午4:26:48
 */
@Component
public class SessionUserUtil {
    private static final Logger logger = LoggerFactory.getLogger(SessionUserUtil.class);
//    private static Session getSession() {
//        return SecurityUtils.getSubject().getSession();
//    }
    @Autowired
    private UserService userService;

    /**
     * 获取登录用户信息
     */
    @SuppressWarnings("unchecked")


    public DUser getUser() {
        DUser user = null;
        String token = getAuthenticationToken();
        boolean isValid = PasswordHelper.validateToken(token);
        if (isValid) {
            String username = PasswordHelper.getUserName(token);
            user = userService.getUserByLoginName(username);
        }

        Session session = SecurityUtils.getSubject().getSession();
        User user1 = (User) session.getAttribute(User.KEY);
        return user;
    }


    /**
     * 设置session属性
     *
     * @param key
     * @param value
     */
    public <T> void set(String key, T value) {
        getUser().put(key, value);
    }

    /**
     * 获取session属性值
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T> T get(String key) {
        return (T) getUser().get(key);
    }


    public String getAuthenticationToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getHeader(LoginHandlerInterceptor.AUTH_TOKEN_HEADER);
    }
}
